package com.nnnu.wsnackshop.controller.admin;


import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.pojo.dto.AssignPermissionDTO;
import com.nnnu.wsnackshop.pojo.vo.PermissionVO;
import com.nnnu.wsnackshop.pojo.vo.RolePermissionVO;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IRolePermissionsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色-权限关联 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("adminRolePermissionsController")
@RequestMapping("/api/admin/role-permissions")
@Slf4j
@Tag(name = "管理端角色权限接口")
@RequiredArgsConstructor
public class RolePermissionsController {

    private final IRolePermissionsService permsService;

    @Operation(summary = "获取角色已分配权限", description = "仅 superAdmin 或 admin 且拥有 role:read 权限可访问")
    @GetMapping("/{roleId}")
    @RequiresRoles(value = {"superAdmin","admin"}, logical = Logical.OR)
    @RequiresPermissions("role:read")
    public Result<RolePermissionVO> getRolePermissions(
            @PathVariable @Parameter(description = "角色ID", in = ParameterIn.PATH) Long roleId) {
        log.info("查询角色({})已分配权限", roleId);
        Set<Integer> perms = permsService.getPermissionsByRole(roleId);
        RolePermissionVO vo = new RolePermissionVO();
        vo.setRoleId(roleId);
        vo.setPermissionIds(perms);
        return Result.success(vo);
    }

    @Operation(summary = "管理员分配权限给角色", description = "仅 superAdmin 且拥有 role:assign_permissions 权限可访问")
    @PostMapping
    @RequiresRoles("superAdmin")
    @RequiresPermissions("role:assign_permissions")
    public Result<Void> assignPermissions(
            @Valid @RequestBody @Parameter(description = "角色权限信息") AssignPermissionDTO dto) {
        log.info("管理员分配权限：{}", dto);
        permsService.assignPermissions(dto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "获取所有可用权限", description = "仅 superAdmin 或 admin 可访问")
    @GetMapping
    @RequiresRoles(value = {"superAdmin","admin"}, logical = org.apache.shiro.authz.annotation.Logical.OR)
    @RequiresPermissions("role:read")
    public Result<List<PermissionVO>> listAll() {
        log.info("获取所有可用权限");
        List<PermissionVO> list = permsService.listAllPermissions();
        return Result.success(list,MessageConstants.SELECT_OK);
    }
}

